import java.util.List;
import java.util.LinkedList;

public class SintaxRule{
    private List<Production> productions;
    private String id;
    private String type;
    private int position;

    public SintaxRule (){
		this.productions=new LinkedList<Production>();
		this.id="";
		this.type="";
		this.position=-1;
    }
    
    public SintaxRule(String id){
		this.id=id;
		this.productions=new LinkedList<Production>();
		this.type="";
		this.position=-1;
    }
    
    public SintaxRule(String id, List<Production> productions){
		this.id=id;
		this.productions=productions;
		this.type="";
		this.position=-1;
    }

	public SintaxRule(int pos,List<Production> productions,String type){
		this.id="";
		this.productions=productions;
		this.type=type;
		this.position=pos;
	}
    
    public List<Production> getProduction(){
		return this.productions;
    }

    public String getId(){
		return this.id;
    }

    public void addProduction(Production p){
		this.productions.add(p);
    }

    public void setId(String id){
		this.id=id;
    }

    public void setType(String type){
		this.type=type;
    }
    
    public String getType(){
		return this.type;
    }

    public void setProduction(List<Production> p){
	this.productions=p;
    }

    public void setPosition(int position){
		this.position=position;
    }
    
    public int getPosition(){
		return this.position;
    }

    public SintaxRule GLC2EBNF(){
	SintaxRule sr = new SintaxRule(this.getId());
	SintaxRule s;
	int index=-1;
	Production p, innerp;
	for(int i=0;i<productions.size();i++){
	    p=new Production();
	    for(int j=0;j<productions.get(i).getSimbols().size();j++){
		if(!productions.get(i).getSimbols().get(j).getValue().equals(getId())){
		    p.addSimbol(productions.get(i).getSimbols().get(j));
		}else{
		    index=productions.get(i).getSimbols().size()-j-1;
		    s=new SintaxRule();
		    s.setPosition(index);
		    s.setType("repeated");
		    p.addSRSimbol(s);
		}
	    }
	    sr.addProduction(p);
	}

	for(int i=0;i<sr.getProduction().size();i++){
	    for(int k=0;k<sr.getProduction().get(i).getSRSimbols().size();k++){
		for(int j=0;j<sr.getProduction().size();j++){
		    innerp=new Production();
		    innerp.addTerms(sr.getProduction().get(j).getSimbols(),new LinkedList<SintaxRule>());
		    sr.getProduction().get(i).getSRSimbols().get(k).addProduction(innerp);
		}
	    }
	}
	return sr;
    }

    public String toString(){
	String s="";
		
	if(id!=""){
	    s+=getId() + " = ";
	    for(int i=productions.size()-1;i>=0;i--){
		s+=productions.get(i).toString();
		if(i!=0)s+="| ";
		else s+="; ";
	    }

	}else{
	    String p="";
	    for(int i=productions.size()-1;i>=0;i--){
		p+=productions.get(i).toString();
		if(i!=0)p+="| ";
	    }
	    if(getType()=="optional")s+="[ "+p+"] ";
	    else if(getType()=="repeated")s+="{ "+p+"} ";
	    else if(getType()=="grouped")s+="( "+p+") ";
	}
	return s;
    }
}
